package com.heoller.service.template;

import cn.hutool.core.util.CharUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Objects;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.annotation.PostConstruct;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Service;

/**
 * @author huliang
 * @date 2021-11-23 16:04
 */
@Service
public class TemplateService {

    private Configuration configuration;

    @PostConstruct
    public void init() {
        configuration = new Configuration(Configuration.VERSION_2_3_28);
        configuration.setDefaultEncoding("UTF-8");
        // 指定模板的路径
        try {
            configuration.setClassForTemplateLoading(this.getClass(), "/");
        } catch (Exception e) {
            // do nothing
        }
    }

    public Template getTemplate(String module, String name) {
        String templateName = "templates" + CharUtil.SLASH + module + CharUtil.SLASH + name;
        try {
            return configuration.getTemplate(templateName);
        } catch (IOException e) {
            // do nothing
        }
        return null;
    }
    public void writeFile(ZipOutputStream zip, String filePath, Template template, Object param) {
        if (Objects.isNull(template)) {
            return;
        }
        try (StringWriter sw = new StringWriter()) {
            template.process(param, sw);
            zip.putNextEntry(new ZipEntry(filePath));
            IOUtils.write(sw.toString(), zip, "UTF-8");
            IOUtils.closeQuietly(sw);
            zip.closeEntry();
        } catch (Exception e) {
            // do nothing
        }
    }

    public void writeDirectory(ZipOutputStream zip, String dirPath) {
        try {
            zip.putNextEntry(new ZipEntry(dirPath));
            zip.closeEntry();
        } catch (Exception e) {
            // do nothing
        }
    }
}
